<template>
  <div ref="containerRef">
    <div class="text-[26px] font-bold">
      <button class="pr-3" :class="[ activeTab === 'mycomment'? 'opacity-100' : 'opacity-30' ]" @click="handleMycomment">My comments</button>
      <a-divider direction="vertical" :size="3" />
      <button class="pl-3" :class="[ activeTab === 'commentme'? 'opacity-100' : 'opacity-30' ]" @click="handleCommentme">Comments on my content</button>
    </div>
    <img src="@/assets/images/line-light.png"></img>
    <a-list
      v-if="activeTab === 'mycomment'"
      class="list-demo-action-layout"
      :bordered="false"
      :split="false"
      :max-height="dynamicHeight"
      :data="mycommentData"
      @reach-bottom="fetchMycommentData(true)" 
      :scrollbar="mycommentScrollbar"
    >
      <template #item="{ item }">
        <a-list-item class="list-demo-item" action-layout="vertical">
          <template #actions>
            <span class="flex items-center h-[24px]">
            </span>
            <div class="absolute right-4">
              <span class="text-[16px] text-primary font-bold pr-2">{{ getMonthName(item.createAt) }}</span>
              <span class="text-[16px] font-bold pr-2">{{ getDayAndYear(item.createAt) }}</span>
              <span class="text-[16px] text-primary font-bold">{{ formatTime(item.createAt) }}</span>
            </div>
          </template>
          <template #extra>
            <a-button type="primary" style="background-color: #FFAB7E; width: 100px;" shape="round">view</a-button>
          </template>
          <a-list-item-meta>
            <template #title>
              <div class="text-[18px] font-bold">
                {{ item.content }}
              </div>
            </template>
            <template #description>
              <div class="text-[16px]">
                {{ item.parent.title || item.parent.content }}
              </div>
            </template>
          </a-list-item-meta>
        </a-list-item>
      </template>
    </a-list>
    <a-list
      v-if="activeTab === 'commentme'"
      class="list-demo-action-layout"
      :bordered="false"
      :split="false"
      :max-height="dynamicHeight"
      :data="commentmeData"
      @reach-bottom="fetchCommentmeData(true)" 
      :scrollbar="commentmeScrollbar"
    >
      <template #item="{ item }">
        <a-list-item class="list-demo-item" action-layout="vertical">
          <template #actions>
            <span class="flex items-center h-[24px]">
            </span>
            <div class="absolute right-4">
              <span class="text-[16px] text-primary font-bold pr-2">{{ getMonthName(item.createAt) }}</span>
              <span class="text-[16px] font-bold pr-2">{{ getDayAndYear(item.createAt) }}</span>
              <span class="text-[16px] text-primary font-bold">{{ formatTime(item.createAt) }}</span>
            </div>
          </template>
          <template #extra>
            <a-button type="primary" style="background-color: #FFAB7E; width: 100px;" shape="round">view</a-button>
          </template>
          <a-list-item-meta>
            <template #title>
              <div class="text-[18px] font-bold">
                {{ item.content }}
              </div>
            </template>
            <template #description>
              <div class="text-[16px]">
                {{ item.parent.title || item.parent.content }}
              </div>
            </template>
          </a-list-item-meta>
        </a-list-item>
      </template>
    </a-list>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { getMonthName, getDayAndYear, formatTime } from '@/utils/tool'
import { myReplyListApi, replyDetailApi } from '@/api/reply';
import { topicDetailApi } from '@/api/topic';
import { myMessageListApi } from '@/api/message';

// Props 定义
interface Props {
  uid?: string
}

const props = withDefaults(defineProps<Props>(), {
  uid: () => localStorage.getItem('uid') || ''
})

const activeTab = ref('mycomment')

// 数据定义
const mycommentData = ref([] as any[])
const mycommentScrollbar = ref(true)

const mycommentQuery: any = ref({
  limit: 10,
  endAt: Date.now()
})
const commentmeData = ref([] as any[])
const commentmeScrollbar = ref(true)

const commentmeQuery: any = ref({
  limit: 10,
  endAt: Date.now()
})

const handleMycomment = () => {
  activeTab.value = 'mycomment'
  mycommentData.value = []
  mycommentQuery.value = {
    limit: 10,
    endAt: Date.now()
  }
}

const handleCommentme = () => {
  activeTab.value = 'commentme'
  commentmeData.value = []
  commentmeQuery.value = {
    limit: 10,
    endAt: Date.now()
  }
}

// 获取问答列表
const fetchMycommentData = (isLoadMore = false) => {
  if(isLoadMore&&mycommentData.value.length > 0) {
    mycommentQuery.value.endAt = mycommentData.value[mycommentData.value.length - 1].cts
  } else {
    mycommentQuery.value.endAt = Date.now()
    mycommentData.value = []
  }
  myReplyListApi(mycommentQuery.value).then(async (res: any) => {
    if (res.code === 0) {
      const promises = res.data.map(async (item: any) => {
        let detail: any = await getReplyDetail(item.replyId)
        if(item.parentReplyId) {
          let parent = await getReplyDetail(item.parentReplyId)
          detail.parent = parent
        } else {
          let post = await getPostDetail(item.moduleId)
          detail.parent = post
        }
        return { ...detail }
      })
      // 使用 Promise.all 来等待所有 Promise 完成，并获取结果
      await Promise.all(promises).then((results) => {
        mycommentData.value = mycommentData.value.concat(results)
        console.log(mycommentData.value)
      })
    }
  })
}

const getReplyDetail = (rid: string) => {
  return new Promise((resolve) => {
		replyDetailApi(rid).then((res: any) => {
			if(res.code === 0) {
				resolve(res.data)
			} else {
				resolve({})
			}
		}).catch(() => {
			resolve({})
		})
	})
}

// 获取帖子详情
const getPostDetail = (tid: string): Promise<any> => {
  return new Promise((resolve) => {
    topicDetailApi(tid, 'display').then((res: any) => {
      if(res.code === 0) {
        resolve(res.data)
      } else {
        resolve({})
      }
    }).catch(() => {
      resolve({})
    })
  })
}

const fetchCommentmeData = (isLoadMore = false) => {
  if(isLoadMore&&commentmeData.value.length > 0) {
    commentmeQuery.value.endAt = commentmeData.value[commentmeData.value.length - 1].cts
  } else {
    commentmeQuery.value.endAt = Date.now()
    commentmeData.value = []
  }
  myMessageListApi(commentmeQuery.value).then(async (res: any) => {
    if (res.code === 0) {
      const promises = res.data.map(async (item: any) => {
        let detail: any = await getReplyDetail(item.recordId)
        if(item.parentRecordId) {
          let parent = await getReplyDetail(item.parentRecordId)
          detail.parent = parent
        } else {
          let post = await getPostDetail(item.moduleId)
          detail.parent = post
        }
        return { ...detail }
      })
      // 使用 Promise.all 来等待所有 Promise 完成，并获取结果
      await Promise.all(promises).then((results) => {
        commentmeData.value = commentmeData.value.concat(results)
        console.log(commentmeData.value)
      })
    }
  })
}

// 暴露方法给父组件
defineExpose({
  fetchMycommentData
})

// 窗口高度和组件元素引用
// 获取整个文档的滚动高度
const windowHeight = ref(document.documentElement.scrollHeight)
const containerRef = ref<HTMLElement>()

// 动态计算列表的最大高度
const dynamicHeight = computed(() => {
  if (!containerRef.value) return 240 // 默认值
  
  const rect = containerRef.value.getBoundingClientRect()
  const availableHeight = windowHeight.value - rect.top
  
  return Math.max(300, availableHeight) // 提高最小高度到300px
})

// 监听窗口大小变化
const handleResize = () => {
  windowHeight.value = window.innerHeight
}

// 组件挂载时获取数据
onMounted(() => {
  window.addEventListener('resize', handleResize)
  nextTick(() => {
    // 确保DOM渲染完成后再计算高度
  })
})

// 组件卸载时清理事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.list-demo-item {
  background-color: #EBECF8;
  margin: 16px 32px 16px 0;
  border-radius: 10px;
}
</style>